package com.huluobo.a2307douyindemo.video

import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.view.animation.BounceInterpolator
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.adapter.CommentAdapter
import com.huluobo.a2307douyindemo.adapter.MultiVideoAdapter
import com.huluobo.a2307douyindemo.adapter.VideosAdapter
import com.huluobo.a2307douyindemo.databinding.FragmentVideoBinding
import com.huluobo.a2307douyindemo.live.LiveActivity
import com.huluobo.a2307douyindemo.login.LoginActivity
import com.huluobo.lib_base.bean.VideoBean
import com.huluobo.lib_base.event.MessageEvent
import com.huluobo.lib_base.mvvm.BaseFragment
import com.huluobo.lib_base.net.Const
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.sql.RowId

@AndroidEntryPoint
class VideoFragment : BaseFragment<FragmentVideoBinding, VideoViewModel>() {
    private lateinit var videosAdapter: MultiVideoAdapter
    private lateinit var commentAdapter: CommentAdapter

    //识别当前展示的item的下标
    private var currentPosition = 0

    //获取当前播放器
    private lateinit var player: StandardGSYVideoPlayer
    override fun initData() {
        vm.getVideos(2, 10)
        vm.getVideosSuccess.observe(this) {
            //清空adapter数据源
            videosAdapter.data.clear()
            //添加adapter数据源
            videosAdapter.data.addAll(it)
            //刷新适配器
            videosAdapter.notifyDataSetChanged()
        }

        vm.likeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            //点赞之后需要修改数据源的内容,然后刷新适配器,才能根据数据源的内容让适配器自动匹配图片
            videosAdapter.data[currentPosition].dianzan = 1
            videosAdapter.notifyDataSetChanged()
        }

        vm.unLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].dianzan = 0
            videosAdapter.notifyDataSetChanged()
        }

        vm.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it)
            videosAdapter.data[currentPosition].guanzhu = 1
            videosAdapter.notifyDataSetChanged()
        }

        vm.getCommentSuccess.observe(this) {
            //注意sorted 出现ed的话,必须要有一个变量来接收排序后的集合
            val list = it.sortedByDescending { it.createtime }
            commentAdapter.data.clear()
            commentAdapter.data.addAll(list)
            commentAdapter.notifyDataSetChanged()
        }

        vm.sendCommentSuccess.observe(this) {
            //追加评论到第一条位置
            commentAdapter.data.addAll(0, it)
            commentAdapter.notifyDataSetChanged()

            //获取评论输入框并清空
            val editText = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
            editText.text.clear()
        }

        vm.collectVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
        }
    }

    override fun initView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        binding.videosRv.layoutManager = linearLayoutManager
        videosAdapter = MultiVideoAdapter()
        binding.videosRv.adapter = videosAdapter

        //声明页面辅助器
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.videosRv)

        //当RecyclerView滚动时,需要获取当前页面的下标
        binding.videosRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //通过linearLayoutManager 找到当前正在显示的item的下标
                currentPosition = linearLayoutManager.findFirstVisibleItemPosition()
                //通过下标和adapter,可以获取到当前正在显示的播放器,来控制自动播放
                player =
                    videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_player) as StandardGSYVideoPlayer
                //播放
//                player.startPlayLogic()
            }
        })

        //要想给adapter中的图标添加点击事件,需要先声明该id可点
        videosAdapter.addChildClickViewIds(
            R.id.item_videos_like_iv,
            R.id.item_videos_add_iv,
            R.id.item_videos_close_iv,
            R.id.item_videos_comment_iv,
            R.id.item_videos_comment_send_iv,
            R.id.item_videos_collect_iv,
            R.id.item_videos_share_iv,
            R.id.item_videos_live_cl,
            R.id.item_videos_full_cl
        )

        videosAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (SPUtils.getInstance().getString(Const.PARAM_TOKEN).isNullOrEmpty()) {
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
            } else {
                //获取adapter中点击时的bean
                val videoBean = videosAdapter.data[position]
                when (view.id) {
                    R.id.item_videos_like_iv -> likeVideo(videoBean)
                    R.id.item_videos_add_iv -> followAuth(videoBean)
                    R.id.item_videos_close_iv -> closeComment()
                    R.id.item_videos_comment_iv -> openComment(videoBean)
                    R.id.item_videos_comment_send_iv -> sendComment(videoBean)
                    R.id.item_videos_collect_iv -> collectVideo(videoBean)
                    R.id.item_videos_share_iv -> shareVideo(videoBean)
                    R.id.item_videos_live_cl -> toLive(videoBean)
                    R.id.item_videos_full_cl -> fullScreen()
                }
            }
        }
    }

    private fun fullScreen() {
        //设置自动翻转屏幕
        player.isRotateViewAuto = true
        //设置全屏播放,是否展示动作条,是否展示状态条
        player.startWindowFullscreen(requireActivity(), false, false)
    }

    private fun toLive(videoBean: VideoBean) {
        val intent = Intent(requireContext(), LiveActivity::class.java)
        intent.putExtra(Const.KEY_VIDEO_BEAN, videoBean)
        startActivity(intent)
    }

    //分享视频
    private fun shareVideo(videoBean: VideoBean) {
        //获取分享的缩略图
        val umImage = UMImage(requireContext(), videoBean.videomainimg)
        //设置图片的缩放规则
        umImage.compressStyle = UMImage.CompressStyle.SCALE

        //以web的形式分享内容
        val umWeb = UMWeb(videoBean.videopath)
        //设置分享标题
        umWeb.title = videoBean.authname
        //设置分享缩略图
        umWeb.setThumb(umImage)
        //设置分享描述
        umWeb.description = videoBean.caption

        //触发分享动作
        ShareAction(requireActivity())
            .withMedia(umWeb)
            .open()
    }

    //收藏视频
    private fun collectVideo(videoBean: VideoBean) {
        vm.collectVideo(videoBean)
    }

    //发布评论
    private fun sendComment(videoBean: VideoBean) {
        val editText = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
        //trim() 去空格
        val msg = editText.text.toString().trim()
        if (msg.isNotEmpty()) {
            val map = mutableMapOf<String, Any>()
            map[Const.PARAM_VIDEO_ID] = videoBean.id
            map[Const.PARAM_MSG] = msg
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            vm.sendComment(body)
        }
    }

    private fun openComment(videoBean: VideoBean) {
        //打开评论列表,拦截事件,让事件无法传递回最外层的视频RecyclerView,让事件只在当前评论RecyclerView中触发
        binding.videosRv.setIntercept(false)
        //获取评论布局
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        if (commentLayout != null) {
            commentLayout.visibility = View.VISIBLE
            //获取每一个评论布局
            val commentRv =
                videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_rv) as RecyclerView
            commentRv.layoutManager = LinearLayoutManager(requireContext())
            commentAdapter = CommentAdapter(vm, videoBean.id, this)
            commentRv.adapter = commentAdapter

            //加载进入动画
            val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
            animIn.duration = 500
            animIn.interpolator = BounceInterpolator()
            animIn.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                    //加载评论数据
                    vm.getComment(videoBean.id)

                }

                override fun onAnimationEnd(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animIn)
        }
    }

    private fun closeComment() {
        //获取评论布局
        val commentLayout = videosAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        if (commentLayout != null) {
            //加载进入动画
            val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
            animOut.duration = 500
            animOut.interpolator = AccelerateInterpolator()
            animOut.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    //动画结束的时候,隐藏掉评论布局
                    commentLayout.visibility = View.GONE
                    binding.videosRv.setIntercept(true)
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animOut)
        }
    }

    //关注
    private fun followAuth(videoBean: VideoBean) {
        val map = mutableMapOf<String, String>()
        map[Const.PARAM_AUTH_NAME] = videoBean.authname
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        vm.followAuth(body)
    }

    //点赞
    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.dianzan == 0) {
            //触发点赞方法
            vm.likeVideo(videoBean.id)
        } else {
            //触发取消点方法
            vm.unLikeVideo(videoBean.id)
        }
    }

    override fun onEvent(event: MessageEvent) {
        Log.e("TagA", "video接受:${event.message}")
    }
}